<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品品牌" prop="brandName">
        <el-input
          v-model="queryParams.brandName"
          placeholder="请输入商品品牌"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['goods:info:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['goods:info:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['goods:info:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['goods:info:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <div id="container" style="height: 1000px"></div>
    <el-table
      v-loading="loading"
      :data="attrList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品编号" align="center" prop="id" />
      <el-table-column label="商品名称" align="center" prop="goodsName" />
      <el-table-column label="商品SPU" align="center" prop="spuCode" />
      <el-table-column label="商品分类" align="center" prop="categoryName" />
      <el-table-column label="商品品牌" align="center" prop="brandName" />
      <el-table-column label="商品图片" align="center" prop="goodsImg">
        <template slot-scope="scope">
          <image-preview
            :src="scope.row.goodsImg"
            :width="50"
            :height="50"
          ></image-preview>
        </template>
      </el-table-column>
      <el-table-column label="商品价格" align="center" prop="goodsPrice" />
      <el-table-column label="上架状态" align="center" prop="publishStatus">
        <template slot-scope="scope">
          <!-- <dict-tag
            :options="dict.type.sys_normal_disable"
            :value="scope.row.enabled"
          /> -->
          {{ scope.row.publishStatus === 1 ? "上架" : "下架" }}
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAttrValues(scope.row)"
            v-hasPermi="['goods:info:attrValues']"
            >关联属性</el-button
          >
          <br />
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['goods:info:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['goods:info:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改规格属性对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品SPU" prop="spuCode">
          <el-input v-model="form.spuCode" placeholder="请输入商品SPU" />
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-cascader
            v-model="form.categoryId"
            :options="GoodsCategoryTree"
            :style="{ width: '100%' }"
            placeholder="请选择级联选择"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="商品品牌" prop="brandId">
          <el-select v-model="form.brandId" placeholder="请选择状态">
            <el-option
              v-for="dict in brandList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上架状态" prop="publishStatus">
          <el-radio-group v-model="form.publishStatus">
            <!-- <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label
            }}</el-radio> -->
            <el-radio label="0">下架</el-radio>
            <el-radio label="1">上架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品图片" prop="goodsImg">
          <image-upload v-model="form.goodsImg" />
        </el-form-item>
        <el-form-item label="商品描述" prop="goodsDesc">
          <el-input
            v-model="form.goodsDesc"
            type="textarea"
            placeholder="请输入商品描述"
          />
        </el-form-item>
        <el-form-item label="商品价格" prop="goodsPrice">
          <el-input
            v-model="form.goodsPrice"
            placeholder="请输入商品价格"
            type="number"
          />
        </el-form-item>
        <el-form-item label="排序值" prop="orderNum">
          <el-input
            v-model="form.orderNum"
            placeholder="请输入排序值"
            type="number"
          />
        </el-form-item>
        <el-form-item label="商品主图" prop="mainPictures">
          <image-upload v-model="form.mainPictures" />
        </el-form-item>
        <el-form-item label="商品详情" prop="detailsPictures">
          <image-upload v-model="form.detailsPictures" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入排序值" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import * as echarts from "echarts";
import {
  listAttr,
  getAttr,
  delAttr,
  addAttr,
  updateAttr,
  cateGoryTreeSelect,
  getBrandAll,
} from "@/api/goods/goodsInfo";

export default {
  name: "Attr",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      goodsNameList: [],
      goodsPriceList: [],
      imgFileList: [],
      GoodsCategoryTree: [],
      // 品牌信息
      brandList: [],
      imageUrl: "",
      // 日期范围
      dateRange: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 规格属性表格数据
      attrList: [],
      shabi: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsName: null,
        brandName: null,
        orderNum: null,
        enabled: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        goodsName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" },
        ],
        spuCode: [
          { required: true, message: "商品SPU不能为空", trigger: "blur" },
        ],
        categoryId: [
          { required: true, message: "商品分类不能为空", trigger: "blur" },
        ],
        brandId: [
          { required: true, message: "商品品牌不能为空", trigger: "blur" },
        ],
        publishStatus: [
          { required: true, message: "请选择上架状态", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getCateGoryTree();
    this.getBrandList();
  },
  methods: {
    getBrandList() {
      getBrandAll(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.brandList = response.rows.map((item) => ({
            value: item.id,
            label: item.name,
          }));
        }
      );
    },
    handleAttrValues(row) {
      const goodsId = row.id;
      this.$router.push("/goods/attr/infoAttrValues/" + goodsId);
    },
    handleAuthRole(row) {
      const id = row.id;
      this.$router.push("/");
    },
    getCateGoryTree() {
      cateGoryTreeSelect().then((response) => {
        // 转换数据格式
        const newGoodsCategoryTree = response.map((item) => {
          return {
            label: item.name,
            children: item.children.map((child) => {
              return {
                value: child.id,
                label: child.name,
              };
            }),
          };
        });
        this.GoodsCategoryTree = newGoodsCategoryTree;
      });
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    drawChart() {
      console.log("1231231" + JSON.stringify(this.attrList.map((item) => item.goodsName), null, 2));
      this.goodsNameList = this.attrList.map((item) => item.goodsName);
      this.goodsPriceList = this.attrList.map((item) => item.goodsPrice);
      var option = {
      xAxis: {
        type: "category",
        data: this.goodsNameList,
      },
      yAxis: {
        type: "value",
      },
      series: [
        {
          data: this.goodsPriceList,
          type: "bar",
        },
      ],
    };
    if (document.getElementById("container")) {
      var myChart = echarts.init(document.getElementById("container"));
      // 假设 option 已正确定义并在作用域内
      myChart.setOption(option);
    }
    },
    /** 查询规格属性列表 */
    getList() {
      this.loading = true;
      listAttr(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.attrList = response.rows;
          this.total = response.total;
          this.loading = false;
          this.drawChart();
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        goodsName: null,
        spuCode: null,
        categoryId: null,
        brandId: null,
        goodsImg: null,
        goodsDesc: null,
        goodsPrice: null,
        publishStatus: null,
        orderNum: null,
        mainPictures: null,
        detailsPictures: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getAttr(id).then((response) => {
        this.form = response.data;
        // 选中默认的类型节点
        for (const category of this.GoodsCategoryTree) {
          for (const child of category.children || []) {
            if (child.label === this.form.categoryName) {
              this.form.categoryId = child.value;
            }
          }
        }
        // 选中默认的品牌
        for (const brand of this.brandList) {
          if (brand.label === this.form.brandName) {
            this.form.brandId = brand.value;
          }
        }

        if (this.form.publishStatus === 0) {
          this.form.publishStatus = "0"; // 确保是字符串类型，与 el-radio 的 label 类型一致
        } else if (this.form.publishStatus === 1) {
          this.form.publishStatus = "1";
        }
        console.log("form:" + JSON.stringify(this.form, null, 2));

        this.open = true;
        this.title = "修改商品信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log("form前:" + JSON.stringify(this.form, null, 2));
      this.form.categoryId = this.form.categoryId[1] || this.form.categoryId;
      console.log("form后:" + JSON.stringify(this.form, null, 2));

      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateAttr(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAttr(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除商品信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return delAttr(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "goods/info/export",
        {
          ...this.queryParams,
        },
        `info_${new Date().getTime()}.xlsx`
      );
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "goods/info/importTemplate",
        {},
        `attr_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 提交上传文件
    submitFileForm() {
      console.log(this.form);
      this.$refs.upload.submit();
    },
  },
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
